/****

    activequant - activestocks.eu

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

	
	contact  : contact@activestocks.eu
    homepage : http://www.activestocks.eu

****/
package org.activequant.data.util;

import java.lang.reflect.Array;
import java.util.Calendar;
import java.util.Vector;

import org.activequant.core.domainmodel.data.MarketDataEntity;
import org.activequant.core.domainmodel.data.TimeSeries;
import org.activequant.core.types.TimeStamp;
import org.activequant.core.util.TimeSeriesUtils;
import org.apache.log4j.Logger;



/**
 * DateGrid&lt;T extends MarketDataEntity&lt;T&gt;&gt;. Holds the following associated variables:
 * <ul>
 * <li>clazz(Class&lt;T&gt;)</li>
 * <li>calendar(Calendar)</li>
 * <li>dates(TimeStamp[])</li>
 * <li>alignedSeries(TimeSeries&lt;T&gt;[])</li>
 * </ul>
 * <br>
 * <b>History:</b><br>
 *  - [08.11.2006] Created (Erik Nijkamp)<br>
 *
 *  @author Erik Nijkamp
 */
public class DateGrid<T extends MarketDataEntity<T>> {
	
	protected final static Logger log = Logger.getLogger(DateGrid.class);
	/**
	 * private final Class&lt;T&gt; clazz;
	 */
	private final Class<T> clazz;
	/**
	 * private Calendar calendar = Calendar.getInstance();
	 */
	private Calendar calendar = Calendar.getInstance();
	/**
	 * private TimeStamp [] dates;
	 */
	private TimeStamp [] dates;
	/**
	 * private TimeSeries&lt;T&gt;[] alignedSeries;
	 */
	private TimeSeries<T>[] alignedSeries;
	/**
	 * constructs a DateGrid&lt;T extends MarketDataEntity&lt;T&gt;&gt; using the given clazz(Class&lt;T&gt;) to set its associated clazz(Class&lt;T&gt;).<br/>
	 * Then it finds the earliestDate(TimeStamp) and latestDate(TimeStamp) among the timeStamps in the given series(TimeSeries&lt;T&gt;...).<br/>
	 * Sets the associated dates(TimeStamp[]) with the values in that earliestDate-latestDate(TimeStamp) interval (but in the opposite order) using a 1 DAY step.<br/>
	 * Sets the associated calendar(Calendar) with the last of those values (the one closest to the latestDate(TimeStamp))<br/>
	 * Sets the associated alignedSeries(TimeSeries&lt;T&gt;[]) with a filtered/aligned version of the given series(TimeSeries&lt;T&gt;...). The filtered version keeps only the elements from the original whose 
	 * timeStamp(TimeStamp) is in the associated dates(TimeStamp[]). Everything else gets filled out with a new appropriate element - (<code>Candle</code>, <code>Quote</code> or <code>TradeIndication</code>)
	 * @param clazz
	 * @param series
	 * @throws Exception
	 */
	public DateGrid(Class<T> clazz, TimeSeries<T>... series) throws Exception{	
		// Get start date
		TimeStamp earliestDate = series[0].lastElement().getTimeStamp();
		// Get end date
		TimeStamp latestDate = series[0].firstElement().getTimeStamp();
		for(int i = 1; i < series.length; i++) {
			TimeStamp date = series[i].lastElement().getTimeStamp();
			if(date.isBefore(earliestDate))
				earliestDate = date;
			if(date.isAfter(latestDate))
				latestDate = date;
		}
		
		// log
		log.debug("earliest date = " + earliestDate + " latest date = " + latestDate);
		assert(earliestDate.isBefore(latestDate));
		
		// Build date list
		buildDays(earliestDate, latestDate);
		
		this.clazz = clazz;
		// Align series
		alignSeries(series);		
	}
	/**
	 * <strong>1.</strong> Sets the associated dates(TimeStamp[]) with the values in the given start-end(TimeStamp) interval (but in the opposite order) using a 1 DAY step.<br/>
	 * <strong>2.</strong> Sets the associated calendar(Calendar) with the last of those values (the one closest to the given end(TimeStamp))
	 * @param start
	 * @param end
	 */
	private void buildDays(TimeStamp start, TimeStamp end) {
		Vector<TimeStamp> datesVector = new Vector<TimeStamp>();
		calendar.setTime(start.getDate());
		while(!calendar.getTime().after(end.getDate())) {
			datesVector.add(0, new TimeStamp(calendar.getTime()));
			calendar.add(Calendar.DATE, 1);
		}
		dates = datesVector.toArray(new TimeStamp[datesVector.size()]);
	}
	
	/**
	 * The given series(S...) is an array of the TimeSeries&lt;T&gt; subclasses: CandleSeries, QuoteSeries or TradeIndicationSeries.<br/>
	 * This method sets the associated alignedSeries(TimeSeries&lt;T&gt;[]) with a filtered/aligned version of the given series(S...). The filtered version keeps only the elements from the original whose 
	 * timeStamp(TimeStamp) is in the associated dates(TimeStamp[]). Everything else gets filled out with a new appropriate element - (<code>Candle</code>, <code>Quote</code> or <code>TradeIndication</code>)
	 * @param <S>
	 * @param series
	 * @throws Exception
	 */
	private <S extends TimeSeries<T>> void alignSeries(S ... series) throws Exception {
		// New array
		alignedSeries = TimeSeriesUtils.cloneSeries(clazz, series);
		// New data holding all dates
		T[][] data = newArray(series);
		// Fill
		for(int i = 0; i < alignedSeries.length; i++) {
			for(int j = 0; j < dates.length; j++) {
				if(series[i].containsTimeStamp(dates[j])) {
					data[i][j] = series[i].getByTimeStamp(dates[j]);
				} else {
					T entity = newElement(series);
					entity.setTimeStamp(dates[j]);
					data[i][j] = entity;
				}
			}			
		}
		// Apply
		for(int i = 0; i < alignedSeries.length; i++) {
			alignedSeries[i].setEntities(data[i]);
		}
	}
	/**
	 * Returns a new <code>Candle</code>, <code>Quote</code> or <code>TradeIndication</code> instance depending on whether the first element in the given series(TimeSeries&lt;T&gt;...) is
	 * a CandleSeries, QuoteSeries or TradeIndicationSeries.
	 * @param series
	 * @return
	 * @throws Exception
	 */
	private T newElement(TimeSeries<T>... series) throws Exception {
		// Get MarketDataEntity class
		Class<T> clazz = TimeSeriesUtils.getEntityClass(series[0]);
		// Return new instance
		return clazz.newInstance();
	}
	/**
	 * returns an empty 2D T[][] array(matrix) whose dimensions are [series.length x dates.length]. The type of each its elements(T) will be either
	 * <code>Candle.class</code>, <code>Quote.class</code> or <code>TradeIndication.class</code> depending on the type of the first element in the
	 * given series(TimeSeries&lt;T&gt;...), which can be either CandleSeries, QuoteSeries or TradeIndicationSeries.
	 * @param series
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private T[][] newArray(TimeSeries<T>... series) {
		// Get MarketDataEntity class
		Class<T> clazz = TimeSeriesUtils.getEntityClass(series[0]);
		// New data holding all dates
		int[] dimensions = new int[] {series.length, dates.length};
		T[][] array = (T[][]) Array.newInstance(clazz, dimensions);
		// Return array
		return array;	
	}
	/**
	 * returns the associated alignedSeries(TimeSeries&lt;T&gt;[])
	 * @return
	 */
	public TimeSeries<T>[] getAlignedSeries() {
		return alignedSeries;
	}
}
